import React from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Table, Card} from 'antd';
import {TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATETIME_FORMAT} from '../constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import {formatAmount, conventEnumValueToString, formatDateTime} from '../utils';
import {injectIntl, language} from './intl';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import {orderTypeHis, partSaleOrderHisStatus, partOrderPriceTermsHis, paymentHisType, shipmentTypeHis} from '../Enum';
import routes from './routes';
import {Link} from 'react-router-dom';
const FormItem = Form.Item;

const orderTypeHisList = orderTypeHis.toList(language);
const partSaleOrderHisStatusList = partSaleOrderHisStatus.toList(language);
const partOrderPriceTermsHisList = partOrderPriceTermsHis.toList(language);
const paymentHisTypeList = paymentHisType.toList(language);
const shipmentTypeHisList = shipmentTypeHis.toList(language);
class QueryHisPanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }

    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    onSelectDealer = data => {
        this.props.onConditionsChange('dealerId', data.id);
        this.props.onQueryDealerChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    render() {
        const {formatMessage} = this.props.intl;
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.queryDealer.id,
            code: this.props.queryDealer.code,
            name: this.props.queryDealer.name
        } : null;
        const columns = [
            {
                title: formatMessage({
                    id: 'queryHisPanel.column.code',
                    defaultMessage: '订单编号'
                }),
                sorter: true,
                dataIndex: 'code',
                render: (text, record) => <Link to={routes.detailHis.format(record.id)} >{text}</Link>
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.customerOrderCode',
                    defaultMessage: '客户订单号'
                }),
                dataIndex: 'customerOrderCode'
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.orderTypeHis',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'orderTypeHis',
                render: text => conventEnumValueToString(orderTypeHis, text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.priceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'priceTerms',
                render: text => conventEnumValueToString(partOrderPriceTermsHis, text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.paymentHisType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentHisType',
                render: text => conventEnumValueToString(paymentHisType, text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.shipmentType',
                    defaultMessage: '发运方式'
                }),
                dataIndex: 'shipmentType',
                render: text => conventEnumValueToString(shipmentTypeHis, text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.piCreateDate',
                    defaultMessage: 'PI生成时间'
                }),
                dataIndex: 'piCreateDate',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.piConfirmDate',
                    defaultMessage: 'PI确定时间'
                }),
                dataIndex: 'piConfirmDate',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.totalAmount',
                    defaultMessage: '订单总金额'
                }),
                dataIndex: 'totalAmount',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.spFreight',
                    defaultMessage: '运费'
                }),
                dataIndex: 'spFreight',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.spInsurance',
                    defaultMessage: '保险费'
                }),
                dataIndex: 'spInsurance',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.submitDate',
                    defaultMessage: '提报时间'
                }),
                dataIndex: 'submitDate',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(partSaleOrderHisStatus, text)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.stockCreatDate',
                    defaultMessage: '备货需求生成时间'
                }),
                dataIndex: 'stockCreatDate',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'queryHisPanel.column.piAttachMent',
                    defaultMessage: 'PI附件'
                }),
                dataIndex: 'piAttachMent'
            }
        ];
        if(!this.props.isDealerUser)
            columns.splice(0, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'queryHisPanel.column.dealer',
                        defaultMessage: '总代'
                    }),
                    dataIndex: 'dealerCode',
                    render: (text, r) => `(${r.dealerCode})${r.dealerName}`
                }
            ]);
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Card>
                    <Row className="form-standard">
                        {!this.props.isDealerUser &&
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryHisPanel.form.dealer',
                                        defaultMessage: '总代'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                    <DealerSelectPanel
                                        value={dealerInfo}
                                        onSelect={this.onSelectDealer} />
                                </FormItem>
                            </Col>
                        }
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryHisPanel.code',
                                defaultMessage: '订单编号'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="code"
                                    value={this.props.conditions.code}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryHisPanel.form.orderTypeHis',
                                    defaultMessage: '订单类型'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="orderTypeHis"
                                    value={this.props.conditions.orderTypeHis}
                                    options={orderTypeHisList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryHisPanel.form.status',
                                    defaultMessage: '状态'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="status"
                                    value={this.props.conditions.status}
                                    options={partSaleOrderHisStatusList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryHisPanel.form.paymentHisType',
                                    defaultMessage: '付款方式'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="paymentHisType"
                                    value={this.props.conditions.paymentHisType}
                                    options={paymentHisTypeList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryHisPanel.form.priceTerms',
                                    defaultMessage: '价格条款'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="priceTerms"
                                    value={this.props.conditions.priceTerms}
                                    options={partOrderPriceTermsHisList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryHisPanel.form.shipmentType',
                                    defaultMessage: '发运方式'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="shipmentType"
                                    value={this.props.conditions.shipmentType}
                                    options={shipmentTypeHisList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryHisPanel.form.submitDate',
                                    defaultMessage: '提报日期'
                                })}
                                {...FORM_OPTIONS.item}>
                                <DateRangePicker name="submitDate" value={this.props.conditions.submitDate}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryHisPanel.form.stockCreatDate',
                                    defaultMessage: '生成备货需求时间'
                                })}
                                {...FORM_OPTIONS.item}>
                                <DateRangePicker name="stockCreatDate" value={this.props.conditions.stockCreatDate}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row className="form-standard">    
                        <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                            <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>
                                {this.props.intl.formatMessage({
                                    id: 'queryHisPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                            <Button key="clear" onClick={this.props.onResetClick}>
                                {this.props.intl.formatMessage({
                                    id: 'queryHisPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                        </Col>
                    </Row>
                </Card>
                <Card>
                    <Table
                        className="white-space-nowrap"
                        columns={columns}
                        dataSource={this.props.list}
                        onChange={this.onChangeSort}
                        rowKey="id"
                        pagination={pagination}
                        loading={this.props.loading || this.state.loading}
                        locale={locale}
                        {...TABLE} />
                </Card>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'queryHisPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

QueryHisPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    querySearch: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onQueryDealerChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    queryDealer: PropTypes.object,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import {
    saveQueryConditionHis,
    resetQueryPanelHis,
    querySearchHis,
    saveQueryDealerHis,
    tableSearchHis
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getConditions = selectorFactory(['page', 'appState', 'queryConditionHis']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealerHis']);
const getData = selectorFactory(['page', 'domainData', 'listHis', 'data']);
const mapStateToProps = state => ({
    loading: state.getIn((['page', 'domainData', 'listHis', 'isFetching'])),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'listHis', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySortHis', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySortHis', 'pageSize']),
    errorMessage: state.getIn(['page', 'domainData', 'listHis', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySortHis', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySortHis', 'sortedOrder']),
    conditions: getConditions(state),
    queryDealer: getQueryDealer(state)
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryConditionHis(name, value)),
    onQueryDealerChange: data => dispatch(saveQueryDealerHis(data)),
    onChangeSort: option => dispatch(tableSearchHis(option)),
    querySearch: () => dispatch(querySearchHis()),
    onResetClick: () => dispatch(resetQueryPanelHis())
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryHisPanel));

